$(function(){ 

    $("#reg_sub").click(function(){ 
		var n = $("#user_tel").val(),
            n2=$("#user_tel2").val(),
			n3=$("#code").val(),
		t = $("#password").val(),
		i = {
		user_tel: n,
        user_tel2:n2,
		code:n3,
		password: t
		};
		$.ajax({ 
			url: reg_url,
			type: "POST",
			data: i,
			dataType: "json",
			success: function(data){
				var data1= eval(data);
				if(data1.status){ 
				  yz_alert_url(data1.info,data1.url);
				}else{ 
				  yz_alert(data1.info);
				}

			},
		});
 	
	});

   //申请提现
   $("#aliapy_sub").click(function()
    {
        var alipay    = $(".alipay").val();
        var alipayname= $(".alipayname").val();
        var price     = $(".price").val();
        var balance   =$("#balance").html();
        var b= balance-price;
        var i={
            alipay:alipay,
            alipayname:alipayname,
            price:price
        };
       if(!isAlipay(alipay)){
            $(".alipay").focus().addClass("error");
            yz_alert("请输入正确的支付宝账号.");
            return false;
        }
        if(!isName(alipayname)){
            $(".alipayname").focus().addClass("error");
            yz_alert("请输入正确的支付宝姓名.");
            return false;
        }
       if(!price){
          $(".price").focus().addClass("error");
          yz_alert("请输入提现金额.");
          return false;
       }
       if(!isPrice(price)){
            $(".price").focus().addClass("error");
            yz_alert("提现金额必须是100倍数,最低提现金额100元!");
            return false;
        }
        $.ajax({
            url: alipay_url,
            type: "POST",
            data: i,
            dataType: "json",
            success: function(json){
              if(json.status){
                var price     = $(".price").val();
                var balance   =$("#balance").html();
                var b= balance-price;
                $("#balance").html(b);
                $(".alipay").attr("disabled",true); 
                $(".alipayname").attr("disabled",true); 
                $(".price").val("");
              } 
               yz_alert(json.info);
            }

        });
        

    });



});





//获取提现类型
function get_type(type)
{
  if(type==1){
    return "支付宝";
  }else{
    return "话费充值";
  }
}

//获取提现状态
function get_status(status){
   if(status==1){
      return "处理中";
   }else if (status==2) {
      return "失败";
   }else if (status==3){
      return "拒绝";
   }else if (status==4){
      return "成功";
   }else{
     return "错误";
   }
}

//时间戳格式化
function get_time(nS) {       
      return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");        
   }  


/*
* 封装layer提示框
*/
function yz_alert(msg){ 
  layer.open({
    content: msg,
    btn: ['确定']
  });
  
  return false;
}

//跳转提示
function yz_alert_url(msg,url){ 
   layer.open({
    title: '提示',
    content: msg,
    btn: ['好'],
    yes: function(index){
        t_url(url);
        layer.close(index);
    },
	no:function(){ 
	    $("#user_tel").val("");
		$("#password").val("");
		t_url("/User/login");
	}
});
}

//验证支付宝账号
function isAlipay(value) {
     if (!/(^(13[0-9]|15[0-9]|18[0-9]|14[0-9]|17[0-9])[0-9]{8}$)|(^([\w-\.]+)@([\w-]+\.)+([a-zA-Z]{2,4})$)/.test(value)) {
        return false;
    }else{
        return true;
    }
 }

 //验证姓名
 function isName(value)
 {
    if (!/^[\u4e00-\u9fa5]+$/.test(value) || value.length < 2 || value.length >5) {
        return false;
    }else{
        return true;
    }
 }
 
//验证提现金额
function isPrice(value)
{   
    if (!/^[1-9]{1}[0]{1}[0]{1}[0]*?$/.test(value)) {
        return false;
    }else{
        return true;
    }  
}

/**
** T_UEL 跳转
**/

function t_url(url){ 
  location.href=url;
}



(function(factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery, window, document);
    }
}(function($, window, document, undefined) {


    /*************************策略对象*****************************/

    var RULES = {
        isNonEmpty: function(value, errorMsg) {
            //不能为空
            if (!value.length) {
                return errorMsg;
            }
        },
        minLength: function(value, length, errorMsg) {
            //大于
            if (value.length < length) {
                return errorMsg;
            }
        },
        maxLength: function(value, length, errorMsg) {
            //小于
            if (value.length < length) {
                return errorMsg;
            }
        },
        isMobile: function(value, errorMsg) {
            //是否为手机号码
            if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
                return errorMsg;
            }
        },
        isEmail: function(value, errorMsg) {
            //是否为邮箱
            if (!/(^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$)/.test(value)) {
                return errorMsg;
            }
        },
        isAlipay: function(value, errorMsg) {
            //是否为邮箱
             if (!/(^(13[0-9]|15[0-9]|18[0-9]|14[0-9]|17[0-9])[0-9]{8}$)|(^([\w-\.]+)@([\w-]+\.)+([a-zA-Z]{2,4})$)/.test(value)) {
                return errorMsg;
            }
        },
        isPrice: function(value, errorMsg) {
            //是否为邮箱
             if (!/^[1-9]{1}[0]{1}[0]{1}[0]*?$/.test(value)) {
                return errorMsg;
            }
        },
     
        between: function(value, range, errorMsg) {
            //大于小于
            var min = parseInt(range.split('-')[0]);
            var max = parseInt(range.split('-')[1]);
            if (value.length < min || value.length > max) {
                return errorMsg;
            }
        },
        onlyEn: function(value, errorMsg) {
            //纯英文
            if (!/^[A-Za-z]+$/.test(value)) {

            }
        },
        onlyZh: function(value, errorMsg) {
            //纯中文
            if (!/^[\u4e00-\u9fa5]+$/.test(value)) {
                return errorMsg;
            }
        },
        onlyNum: function(value, errorMsg) {
            //数字包含小数
            if (!/^[0-9]+([.][0-9]+){0,1}$/.test(value)) {
                return errorMsg;
            }
        },
        onlyInt: function(value, errorMsg) {
            //整数
            if (!/^[0-9]*$/.test(value)) {
                return errorMsg;
            }
        },
        isChecked: function(value, errorMsg, el) {
            var i = 0;
            var $collection = $(el).find('input:checked');
            if(!$collection.length){
                return errorMsg;
            }
        }
    };

    /*************************Validator类*****************************/

    var setting = {
        type: null,
        onBlur: null,
        onFocus: null,
        onChange: null,
        successTip: true
    };

    var Validator = function() {
        this.cache = [];
    };

    Validator.prototype.add = function(dom, rules) {
        var self = this;
        for (var i = 0, rule; rule = rules[i++];) {
            (function(rule) {
                var strategyAry = rule.strategy.split(':');
                var errorMsg = rule.errorMsg
                self.cache.push(function() {
                    var strategy = strategyAry.shift(); // 前删匹配方式并赋值
                    strategyAry.unshift(dom.value); // 前插value值
                    strategyAry.push(errorMsg); // 后插出错提示
                    strategyAry.push(dom); // 后插dom
                    if (!RULES[strategy]) {
                        $.error('没有' + strategy + '规则，请检查命名或自行定义');
                    }
                    return {
                        errorMsg: RULES[strategy].apply(dom, strategyAry),
                        el: dom
                    };
                });
            }(rule));
        }
    };

    Validator.prototype.start = function() {
        var result;
        for (var i = 0, validatorFunc; validatorFunc = this.cache[i++];) {
            var result = validatorFunc();
            if (setting.successTip) {
                new Validator().showMsg($(result.el), '', 1);
            }
            if (result.errorMsg) {
                return result;
            }

        };
        return true;
    };

    Validator.prototype.showMsg = function(target, msg, status, callback) {
        //status
        // 0 : tip
        // 1 : success
        // 2 : error
        var _current = status ? (status > 1 ? 'error' : 'success') : 'tip';
        var $context = target.parent();
        var $msg = $context.find('.valid_message');
        var _other = target.attr('data-type') || '';
        $msg.remove();
        if(msg){
        $context.removeClass('success tip error').addClass(_current+' '+_other).append('<span class="valid_message">' + msg + '</span>');
        }
    };

    var plugin = {
        init: function(options) {
            var $form = this;
            var $body = $('body');
            var $required = $form.find('.required');
            setting = $.extend(setting, options);

            if (setting.type) {
                $.extend(RULES, setting.type);
            }

            var validator = new Validator();

            $body.on({
                focus: function(event) {
                    var $this = $(this);
                    var _tipMsg = $this.attr('data-tip') || '';
                    var _status = $this.attr('data-status');
                    if (_status === undefined ||!parseInt(_status)) {
                        validator.showMsg($this, _tipMsg);
                    }
                    setting.onFocus ? setting.onFocus.call($this, arguments) : '';
                },
                blur: function(event) {
                    var $this = $(this);
                    var dataValid = $this.attr('data-valid');
                    var validLen = dataValid.split('||');
                    var errCollection = $this.attr('data-error');
                    var errMsgAry = errCollection.split("||");
                    var strategyAry, strategy, errMsg;

                    for (var i = 0; i < validLen.length; i++) {
                        strategyAry = validLen[i].split(':');
                        strategy = strategyAry.shift();
                        strategyAry.unshift(this.value);
                        strategyAry.push(errMsgAry[i]);
                        strategyAry.push(this);
                        errMsg = RULES[strategy].apply(this, strategyAry);
                        if (errMsg) {
                            $this.attr('data-status', 0);
                            validator.showMsg($this, errMsg, 2);
                            break;
                        }
                    };

                    if (!errMsg) {
                        $this.attr('data-status', 1);
                        setting.successTip ? validator.showMsg($this, '', 1) : $this.parent().find('.valid_message').remove();
                    }

                    setting.onBlur ? setting.onBlur.call($this, arguments) : '';
                },
                change: function(event) {
                    setting.onChange ? setting.onChange.call($this, arguments) : '';
                }
            }, '.required');


        },
        submitValidate: function(options) {
            var $form = options || this;
            var $body = $('body');
            var $required = $form.find('.required');
            var validator = new Validator();
            var $target;

            $.each($required, function(index, el) {
                var $el = $(el);
                var dataValid = $el.attr('data-valid');
                var validLen = dataValid.split('||');
                var errCollection = $el.attr('data-error');
                var errMsgAry = errCollection.split("||");
                var ruleAry = [];

                for (var i = 0; i < validLen.length; i++) {
                    ruleAry.push({
                        strategy: validLen[i],
                        errorMsg: errMsgAry[i]
                    });
                };

                validator.add(el, ruleAry);

            });

            var result = validator.start();

            if (result.errorMsg) {
                $target = $(result.el);
                //$target.attr('data-status', 0)[0].focus();
                validator.showMsg($target, result.errorMsg, 2);
                return false;
            }


            return true;
        }
    };

    $.fn.validate = function() {
        var method = arguments[0];
        if (plugin[method]) {
            method = plugin[method];
            arguments = Array.prototype.slice.call(arguments, 1);
        } else if (typeof(method) == 'object' || !method) {
            method = plugin.init;
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.validate Plugin');
            return this;
        }
        return method.apply(this, arguments);
    }

}))
